#!/usr/bin/env perl
use warnings;
use strict;

use DBI;
use CGI;
use Digest::SHA;

# change /path/to/includes to match your setup
BEGIN {
    use constant INCLUDES => '/path/to/includes';
    require(INCLUDES . '/functions.pl');
    require(INCLUDES . '/database.pl');
    require(INCLUDES . '/images.pl');
}

# create database connection
my $dbh = DBI->connect(DB_DBI, DB_USER, DB_PASS);

# get cookie data (login credentials)
my $cgi = CGI->new;
my $c_user = $cgi->cookie('user');

# fetch user credentials
my %user = get_user($dbh, $c_user);

# check user credentials
if (not defined($user{'hash'})) {
    $dbh->disconnect;
    error BAD_CREDS;
} elsif (not ($user{'permissions'} & ACCESS_IMG_UP)) {
    $dbh->disconnect;
    error ACCESS_DENIED;
}

# TODO: check these for "correctness"
# fetch cgi parameters
my ($hash, $hash2, $name, $filename, $thumb, $width, $height, $size, $nws);
$hash = $cgi->param('hash') if (defined($cgi->param('hash')));
$hash2 = $cgi->param('hash2') if (defined($cgi->param('hash2')));
$name = $cgi->param('name') if (defined($cgi->param('name')));
$filename = $cgi->param('filename') if (defined($cgi->param('filename')));
$thumb = $cgi->param('thumbnail') if (defined($cgi->param('thumbnail')));
$width = int($cgi->param('width')) if (defined($cgi->param('width')));
$height = int($cgi->param('height')) if (defined($cgi->param('height')));
$size = int($cgi->param('size')) if (defined($cgi->param('size')));
$nws = int($cgi->param('nws')) if (defined($cgi->param('nws')));

foreach ($hash, $hash2, $name, $filename, $thumb, $width, $height, $size, $nws) {
    if not(defined($_)) {
        $dbh->disconnect;
        error BAD_CGI;
    }
}

# TODO: carefully audit this protocol!
# verify client provided correct hash information
my $sha2obj = Digest::SHA->new(512);
$sha2obj->add(SEED);
my $seed_hash = $sha2obj->hex_digest();
$sha2obj->add(string_zip($hash, $seed_hash));
my $generated_hash = $sha2obj->hex_digest();
if ($generated_hash ne $hash2) {
    $dbh->disconnect;
    error BAD_CREDS;
}

# check for repeat files
if (is_repeat($dbh, $hash)) {
    $dbh->disconnect;
    error DUPE_FILE;
}

# insert image data into database
my $sth = $dbh->prepare(
    "INSERT INTO images (hash, name, filename, thumbnail, width, height, size, nws) " .
    "values (?, ?, ?, ?, ?, ?, ?, ?)");
$sth->execute($hash, $name, $filename, $thumb, $width, $height, $size, $nws);
$sth->finish;

# finished with database connection
$dbh->disconnect;

# return the success response page
html_begin;
html_title "Success";
html_body;
print "        <h1>Success</h1>\n        <p>Success</p>\n";
html_end;
